package validate

import (
	"strings"

	"github.com/go-playground/locales/zh"
	ut "github.com/go-playground/universal-translator"
	"github.com/go-playground/validator/v10"
	zh_translations "github.com/go-playground/validator/v10/translations/zh"

	"project/study-go/logger"
)

var (
	Trans ut.Translator
)

//初始化翻译器
func InitTranslate() {
	zh := zh.New()
	uni := ut.New(zh)
	Trans, _ = uni.GetTranslator("zh")
	err := zh_translations.RegisterDefaultTranslations(Validator, Trans)
	if err != nil {
		logger.UnexpectLogger.Fatalf("register zh translation fail: %s", err)
	}
}

//removeTopStruct 移除翻译后的结构体名字前缀 eg. strucname.fieldname -> fieldname
func removeTopStruct(fields map[string]string) map[string]string {
	ret := map[string]string{}
	for field, value := range fields {
		ret[strings.Split(field, ".")[1]] = value
	}
	return ret
}

//ValidateTranslation 校验翻译错误结果
func ValidateTranslation(err error) interface{} {
	errs := err.(validator.ValidationErrors)
	return removeTopStruct(errs.Translate(Trans))
}

//translate 自定义字段的翻译方法
func translate(trans ut.Translator, fe validator.FieldError) string {
	msg, err := trans.T(fe.Tag(), fe.Field())
	if err != nil {
		panic(err)
	}
	return msg
}

//registerTranslator 为自定义字段添加翻译功能
func registerTranslator(tag string, msg string) validator.RegisterTranslationsFunc {
	return func(trans ut.Translator) error {
		if err := trans.Add(tag, msg, false); err != nil {
			return err
		}
		return nil
	}
}
